# -*- coding: utf-8 -*-

"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".

Replace this with more appropriate tests for your application.
"""

import os
from datetime import datetime

from django.test import TestCase
from django.utils.unittest import skipUnless, skipIf
from django.conf import settings

from financial_daily.utils import RedisUtils
from financial_daily.qa_statistics import QAStatistics
from financial_daily.xml_processors import ChuanwenProcessor
from financial_daily.polarity_check import PolarityCheck
from basic_info.models import Stock, Industry, StockIndustryMap, Concept, StockConceptMap,\
                                Location, StockLocationMap
from companies.models import RumorVerification, DailyMoneyFlow, QA, QAStatisticsResult, StatisticsCategory, QuestionPolarity
from companies.tasks import sync_moneyflow, generate_daily_moneyflow_stats, import_daily_qa


class RumorVerificationTest(TestCase):
    @skipIf(os.environ['DJANGO_SETTINGS_MODULE'].endswith('test'), "Only test this on a local server with web access.")
    def setUp(self):
        self.ylgf, created = Stock.objects.get_or_create(code='002725', short_name='跃岭股份')
        self.dskj, created = Stock.objects.get_or_create(code='300073', short_name='当升科技')

    def test_process_daily_chuanwen(self):
        date_str = '2014-02-09'
        processor = ChuanwenProcessor()
        processor.process(date_str)

        count = RumorVerification.objects.filter(stock=self.ylgf).count()
        self.assertEqual(count, 1)
        count = RumorVerification.objects.filter(stock=self.dskj).count()
        self.assertEqual(count, 1)

class MoneyFlowTests(TestCase):
    @skipUnless(os.environ['DJANGO_SETTINGS_MODULE'].endswith('test'), "Only test this on a test server.")
    def test_generate_daily_moneyflow_stats(self):
        date_str = '2013-11-14'
        ywt = Stock.objects.create(code='002334',
                             short_name=u'英威腾',
                             pinyin_name='ywt',
                             full_name=u'深圳市英威腾电气股份有限公司')  
        pingan = Stock.objects.create(code='000001',
                     short_name=u'平安银行',
                     pinyin_name='payh',
                     full_name=u'平安银行股份有限公司')

        generate_daily_moneyflow_stats(date=date_str)
        money_flow, created = DailyMoneyFlow.objects.get_or_create(date=date_str, stock=ywt)
        self.assertFalse(created)
        money_flow, created = DailyMoneyFlow.objects.get_or_create(date=date_str, stock=pingan)
        self.assertFalse(created)

class PolarityCheckTest(TestCase):
    def setUp(self):
        self.checker = PolarityCheck()
        
    def test_positve(self):
        self.assertEqual(self.checker.get_text_polarity(u"4款手机彩票游戏内部测试成功,何时上市？再给我们透漏一点细节，增加我们股民的信心")[0], QuestionPolarity.POSITIVE)

class CompaniesTests(TestCase):

    date_str = '2014-01-05'
    date = datetime.strptime(date_str, "%Y-%m-%d")
    cycle = 1

    def setUp(self):
        # 创建统计对象
        self.qa_statistics = QAStatistics(self.date, self.cycle)
        
        # 录入测试数据
        redis_host = settings.QA_REDIS_HOST
        redis_port = settings.QA_REDIS_PORT
        redis_db_no = settings.QA_REDIS_DB_NO
        redis_conn = RedisUtils.connect_redis(host=redis_host, port=redis_port, db=redis_db_no)
        members = redis_conn.smembers('QA.2014-01-05')
        for member in members:
            stockcode = redis_conn.hget(member, 'stockcode')
            Stock.objects.get_or_create(code=stockcode, short_name=stockcode, pinyin_name=stockcode, full_name=stockcode, csrc_industry=stockcode, csrc_sub_industry=stockcode)

        import_daily_qa(self.date_str)

        stock_list = ['002353', '000017', '300082', '300074', '002584', '000525', '000972', '300158', '000629']

        industry_jixie, created = Industry.objects.get_or_create(name=u'机械行业')
        industry_huagong, created = Industry.objects.get_or_create(name=u'化工行业')
        industry_dianzi, created = Industry.objects.get_or_create(name=u'电子信息')

        concept_jianzhu, created = Concept.objects.get_or_create(name=u'建筑节能')
        concept_zhaimao, created = Concept.objects.get_or_create(name=u'摘帽概念')
        concept_chukou, created = Concept.objects.get_or_create(name=u'出口退税')

        location_guangdong, created = Location.objects.get_or_create(name=u'广东')
        location_beijing, created = Location.objects.get_or_create(name=u'北京')
        location_shanghai, created = Location.objects.get_or_create(name=u'上海')

        for stock_code in stock_list[:3]:
            stock = Stock.objects.get(code=stock_code)
            StockIndustryMap.objects.get_or_create(stock=stock, industry=industry_jixie)
            StockConceptMap.objects.get_or_create(stock=stock, concept=concept_jianzhu)
            StockLocationMap.objects.get_or_create(stock=stock, location=location_guangdong)

        for stock_code in stock_list[3:6]:
            stock = Stock.objects.get(code=stock_code)
            StockIndustryMap.objects.get_or_create(stock=stock, industry=industry_huagong)
            StockConceptMap.objects.get_or_create(stock=stock, concept=concept_zhaimao)
            StockLocationMap.objects.get_or_create(stock=stock, location=location_beijing)

        for stock_code in stock_list[6:]:
            stock = Stock.objects.get(code=stock_code)
            StockIndustryMap.objects.get_or_create(stock=stock, industry=industry_dianzi)
            StockConceptMap.objects.get_or_create(stock=stock, concept=concept_chukou)
            StockLocationMap.objects.get_or_create(stock=stock, location=location_shanghai)

        self.qa_statistics.get_qa_statistics()
       
    def test_import_qa_daily(self):
        # 数据接入测试
        self.assertEqual(QA.objects.all().count(), 29)
        stock = Stock.objects.get(code='002353')
        self.assertEqual(QA.objects.filter(stock=stock).count(), 11)
    
    def test_statistics_qa_stock(self):
        # 公司测试
                
        qa_result = QAStatisticsResult.objects.get(date=self.date_str, 
                                                   category=StatisticsCategory.COMPANY, 
                                                   name='002353')
        self.assertEqual(qa_result.count, 11)

        qa_result = QAStatisticsResult.objects.get(date=self.date_str, 
                                                   category=StatisticsCategory.COMPANY, 
                                                   name='000525')
        self.assertEqual(qa_result.count, 1)

    def test_statistics_qa_industry(self):
        # 行业测试
        
        qa_result = QAStatisticsResult.objects.get(date=self.date_str, 
                                                   category=StatisticsCategory.INDUSTRY, 
                                                   name=u'机械行业')
        self.assertEqual(qa_result.count, 20)
        
    def test_statistics_qa_concept(self):
        # 概念测试
        
        qa_result = QAStatisticsResult.objects.get(date=self.date_str, 
                                                   category=StatisticsCategory.CONCEPT, 
                                                   name=u'建筑节能')
        self.assertEqual(qa_result.count, 20)
        
    def test_statistics_qa_location(self):
        # 地域测试
        
        qa_result = QAStatisticsResult.objects.get(date=self.date_str, 
                                                   category=StatisticsCategory.LOCATION, 
                                                   name=u'广东')
        self.assertEqual(qa_result.count, 20)
        
    def test_statistics_qa_category(self):
        # 类别测试
                
        qa_result = QAStatisticsResult.objects.get(date=self.date_str, 
                                                   category=StatisticsCategory.QUESTION, 
                                                   name=u'并购重组')
        self.assertEqual(qa_result.count, 4)

